<template>
    <view class="tn-p-sm tn-shadow">
        <view class="checkbox-group">
            <tn-checkbox 
                v-for="item in options" 
                :key="item.value"
                v-model="selectedValues[item.value]" 
                :active-value="1" 
                :inactive-value="0" 
                class="checkbox-item"
                @change="handleChange"
            >
                {{ item.label }}
            </tn-checkbox>
        </view>
    </view>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'

const props = defineProps({
    // 复选框选项数组
    options: {
        type: Array,
        required: true,
        default: () => []
    },
    // v-model绑定值
    modelValue: {
        type: Object,
        default: () => ({})
    }
})

const emit = defineEmits(['update:modelValue'])

// 内部选中状态
const selectedValues = reactive({})

// 初始化选中值
watch(() => props.options, (newOptions) => {
    newOptions.forEach(item => {
        selectedValues[item.value] = props.modelValue[item.value] || 0
    })
}, { immediate: true })

// 监听外部值变化
watch(() => props.modelValue, (newValue) => {
    Object.keys(newValue).forEach(key => {
        if (selectedValues[key] !== undefined) {
            selectedValues[key] = newValue[key]
        }
    })
}, { deep: true })

// 处理选中值变化
const handleChange = () => {
    const result = {}
    Object.keys(selectedValues).forEach(key => {
        result[key] = selectedValues[key]
    })
    emit('update:modelValue', result)
}
</script>

<style scoped>
.checkbox-group {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    padding: 10px;
}

.checkbox-item {
    min-width: 120px;
}
</style> 